package icu.xuyijie.springbootlearning1.chapter6;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 徐一杰
 * @date 2025/03/11 15:32
 * @description 从数据库加载用户
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询数据库，取出数据
        // User user = userMapper.findUser(username);

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        // 意思是往列表里假如一个角色，必须是 ROLE_ 开头
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_student"));
        // 不加 ROLE_ 前缀，加入的就不是角色，而是一条权限
        grantedAuthorities.add(new SimpleGrantedAuthority("delete"));

        return new User(
                username,
                // 因为 security 存储的用户密码都只能是加密过的，所以我们们手动加密一下方便对比
                passwordEncoder.encode("123456"),
                // 角色、权限列表
                grantedAuthorities
        );
    }
}
